package com.hao.demo.zoo.client.grpc;

import com.hao.demo.zoo.client.properties.GrpcProperties;
import com.hao.demo.zoo.entity.DepotsOperateLogEntity;
import com.hao.demo.zoo.protobuf.api.OperateLogRequest;
import com.hao.demo.zoo.protobuf.api.OperateLogResponse;
import com.hao.demo.zoo.protobuf.api.OperateLogResponseList;
import com.hao.demo.zoo.protobuf.api.OperateLogServiceGrpc;
import io.grpc.Channel;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @Description: TODO
 * @Author Hao
 * @Date 2021/6/7 14:44
 * @Version 2.0
 */
@Service
@Slf4j
public class DepotsOperateLogGrpcService {

    @GrpcClient("zoo-server-application")
    Channel serverChannel;
    @Autowired
    private GrpcProperties grpcProperties;

    public List<DepotsOperateLogEntity> getByBusinessId(Integer businessId) {
        long s = System.currentTimeMillis();
        log.debug("getByBusinessId 开始时间：" + s);

        List<DepotsOperateLogEntity> res = new ArrayList<>();

        // 创建同步Stub, 使用通道
        OperateLogServiceGrpc.OperateLogServiceBlockingStub blockingStub = OperateLogServiceGrpc.newBlockingStub(serverChannel);

        // 创建请求
        OperateLogRequest request = OperateLogRequest.newBuilder().setBusinessId(businessId).build();
        // 执行 gRPC 请求 同步
        OperateLogResponseList responseList = blockingStub.withDeadlineAfter(grpcProperties.getTimeout(), TimeUnit.MILLISECONDS)
                .getByBusinessId(request);

        List<OperateLogResponse> list = responseList.getResponseList();
        list.parallelStream().forEach(item -> {
            DepotsOperateLogEntity entity = new DepotsOperateLogEntity();
            BeanUtils.copyProperties(item, entity);
            res.add(entity);
        });

        long e = System.currentTimeMillis();
        log.debug("getByBusinessId 结束时间：" + e);
        log.debug("getByBusinessId 耗时时间：" + (e - s));

        return res;
    }
}
